<?php

require_once 'mailer/plugin.php';

class Mailer
{

	/**
	 * get default service id configure by system
	 * @see Core_Model_Table_Mail_Transport::getDefaultId
	 * @return int
	 */
	static function getDefaultId()
	{
		static $id = null;
		if (null == $id)
		{
			$key = 'core/mail/transport::getDefaultId()';
			if (false == ($id = Cache::instance() -> get($key)))
			{
				$id = Model::getTable('core/mail/transport') -> getDefaultId();
				Cache::instance() -> set($key, $id);
			}
		}
		return $id;
	}

	/**
	 * get mail config with associate id
	 * @see Core_Model_Table_Mail_Transport::get
	 * @param int $id
	 * @return array
	 */
	static function getConfig($id)
	{
		$key = 'core/mail/transport::get()' . $id;
		if (false == ($id = Cache::instance() -> get($key)))
		{
			$config = Model::getTable('core/mail/transport') -> get($id);
			Cache::instance() -> set($key, $config);
		}
		return $config;
	}

	/**
	 * singleton adapter object
	 * @param string|int $id
	 * @param array $config optional
	 * @return Mailer_Adapter
	 */
	static function getTransport($id = NULL, $config = NULL)
	{
		static $transport = array();

		if (null == $id)
		{
			$id = self::getDefaultId();
		}

		if (!isset($transport[$id]))
		{
			if (null == $config)
			{
				$config = self::getConfig($id);
			}

			$service_id = $config['service_id'];
			if ($service_id == 'smtp')
			{
				require_once 'Zend/Mail/Transport/Smtp.php';
				$transport[$id] = new Zend_Mail_Transport_Smtp($config);
			}
			else
			if ($service_id == 'sendmail')
			{
				$transport[$id] = new Zend_Mail_Transport_Sendmail($config);
			}
			else
			{
				$class_name = 'Mailer_Adapter_' . ucfirst($service_id);
				$transport[$id] = new $class_name($config);
			}
		}
		return $transports[$id];
	}

	static function factory($name)
	{
		return new self;
	}

	function send()
	{

	}

	/**
	 * factory message object
	 * @param array $params
	 * @return Mailer_Message
	 */
	static function execute($code, $params, $direct = NULL, $from = NULL, $name = NULL)
	{
		// batch mail plugin from code.

		// batch mail process from params.

		// call params plugin and batch it to execute or insert to queue if needed.
	}

}
